var zookeeper = require('node-zookeeper-client');

var client = zookeeper.createClient('localhost:2181');
var path = process.argv[2] || "/shihui/name";

function listChildren(client, path) {
    client.getChildren(
        path,
        function (event) {
            console.log('Got watcher event: %s', event);
            listChildren(client, path);
        },
        function (error, children, stat) {
            if (error) {
                console.log(
                    'Failed to list children of %s due to: %s.',
                    path,
                    error
                );
                client.close();
                return;
            }
            console.log('Children of %s are: %j length: %s', path, children, children.length);
            // console.log('Children of %s are: %j.', path, children);
            var data=[];
            for(var index in children){
                var child=children[index];
                console.log("child:"+child);
                var childPath=path+"/"+child;
                if(path=="/"){
                    childPath="/"+child;
                }
                data[index]={"name":child,"id":childPath,"path":childPath,"isParent":"true", "parentPath" : path};
            }   
            console.log("data %j", data);
            client.close();
        }
    );
}

client.once('connected', function () {
    console.log('Connected to ZooKeeper.');
    var state = client.getState();
    console.log('Current state is: %s', state);
    listChildren(client, path);
});



client.connect();